<template>
  <div>
    <!-- title -->
    <div>
      <TitleCompound :title="title"></TitleCompound>
    </div>

    <!-- content -->
    <div>
      <p><b><a href="https://cn.vuejs.org/api/reactivity-core.html#watch">watch和watchEffect</a> </b>侦听一个或多个响应式数据源，并在数据源变化时调用所给的回调函数。</p>
      <p>watchEffect不需要指定监听对象，会自动监听其中使用到的变量变化。但是没有了oldValue信息了。</p>
      <!-- 基础类型 -->
      <div>
        <h2>基础类型</h2>
        <p>sum: {{ sum }}</p>
        <el-button @click="add" type="primary">add on</el-button>
        <el-divider></el-divider>
        <p>oldSum: {{ oldSum }}</p>
        <p>newSum: {{ newSum }}</p>
        <el-divider></el-divider>
      </div>
      <!-- 对象类型 -->
      <div>
        <h2>对象类型</h2>
        <!-- <p>person: {{ person }}</p> -->
        <el-table :data="[person]">
          <el-table-column prop="name" label="name"></el-table-column>
          <el-table-column prop="age" label="age"></el-table-column>
          <el-table-column prop="gender" label="gender"></el-table-column>
        </el-table>
        <el-button @click="changePersonName" type="primary">changePersonName</el-button>
      <p>请查看日志，就是在配置了：<b>  immediate: true,</b>，可以捕获到第一次的变化，后续的输出前后都是一样的值，原因在于watch对应的对象的地址并没有变化。所以内容不会修改，只有地址变化之后，才能捕获到前后的值。</p>
        <el-divider></el-divider>
        <el-button @click="addPersonAge" type="primary">addPersonAge</el-button>
        <el-divider></el-divider>
    </div>
      <div></div>

    </div>

  </div>
</template>

<script setup lang="ts">
import TitleCompound from '@/components/TitleCompound.vue';
import type { Person } from '@/types';
import { ref, watch, watchEffect } from 'vue';

const title = "Watch Quickstart"

// 基础类型
const sum = ref(0)

function add(){
  sum.value += 1
}
const oldSum = ref(0)
const newSum = ref(0)
watch(sum, (newVal, oldVal) => {
  console.log(`newVal: ${newVal}, oldVal: ${oldVal}`)
  oldSum.value = oldVal
  newSum.value = newVal
})

// 对象类型
const person = ref<Person>({
  name: "张三",
  age: 18,
  gender: "male",
})
function changePersonName(){
  person.value.name = person.value.name === '张三' ? '李四' : '张三'
}

function addPersonAge() {
  person.value.age += 1
}

const personWatchHandler = watch(person, (newVal, oldVal) => {
  console.log(`newVal: ${newVal.name} - ${newVal.age}, oldVal: ${oldVal ? oldVal.name : ""} - ${oldVal ? oldVal.age : 0}`)

  if(newVal.age > 60) {
    console.log("停止监听")
    personWatchHandler() // 停止监听
  }

}, {
  immediate: true,
  deep: true
})

// watch可以同时监听多个数据
watch([sum, person], (newVal, oldVal) => {
  console.log(`newVal: ${newVal}, oldVal: ${oldVal}`)
}, {
  immediate: true,
  deep: true
})

watchEffect(() => {
  console.log(`WatchEffect: sum: ${sum.value}, person: ${person.value.name} - ${person.value.age}`)
})

</script>

<style lang="scss" scoped></style>
